package br.com.octobite.cashkeeper.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import br.com.octobite.cashkeeper.CashKeeperActivity;
import br.com.octobite.cashkeeper.model.Categoria;

public class CategoriaDAO extends SQLiteOpenHelper {

	private static final int DB_VERSION = 2;
	private static final String DB_NAME = "chashKeeper";
	private static final String CREATE = "CREATE TABLE categoria (id PRIMARY KEY, nome TEXT UNIQUE);";

	public CategoriaDAO(Context context) {
		super(context, DB_NAME, null, DB_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		String ddl = "DROP TABLE IF EXISTS categoria";
		db.execSQL(ddl);
		this.onCreate(db);

	}

	public List<Categoria> getCategorias() {
		String[] nomes = { "id", "nome" };
		Cursor cursor = getWritableDatabase().query("categoria", nomes, null,
				null, null, null, null);
		List<Categoria> categorias = new ArrayList<Categoria>();
		while (cursor.moveToNext()) {
			Categoria c = new Categoria();
			long id = cursor.getLong(0);
			String nome = cursor.getString(1);
			c.setId(id);
			c.setNome(nome);
			categorias.add(c);
		}
		return categorias;
	}

	public void salva(Categoria c) {
		try {
			if (!c.getNome().equals("")) {
				ContentValues cv = new ContentValues();
				cv.put("nome", c.getNome());
				getWritableDatabase().insert("categoria", null, cv);
			}
		} catch (Exception e) {
			Log.i(CashKeeperActivity.TAG, "Nome deve ser unique");
			// TODO avisar que já existe
		}
	}
}
